import moment from 'moment';
import { _ } from 'meteor/underscore';
import { JoinClient } from 'meteor-publish-join';
import { ChannelMessages } from '/imports/models/ChannelMessages';
import { clientChannelMessages } from '../../lib/collections';

let formerLimit = null;
let formerTimestamp = null;
let formerChatContentHeight = null;

Template.channel_chatroom.onCreated(function () {
  Session.set('class.channelChatroom.renderedItemSum', 0);
  
  this.limit = new ReactiveVar(15);
  this.openNotice = new ReactiveVar(false);

  this.autorun(() => {
    this.resultsSub = this.subscribe('get.channelMessages', { channelId: this.data.channel._id }, this.limit.get());
    this.total = JoinClient.get('get.channelMessages.counts');
  });
});

Template.channel_chatroom.onRendered(function () {
  let ps = new PerfectScrollbar('#channel-chatroom-ps');
  let viewport = this.$('#channel-chatroom-ps');
  let viewportHeight = viewport.height();

  this.autorun(() => {
    let sum = Session.get('class.channelChatroom.renderedItemSum');

    if (sum) {
      let chatContentHeight = this.$('#channel-chat-content').height() + 32;
      viewport.scrollTop(Math.round(chatContentHeight));

      if (formerLimit && this.limit.get() != formerLimit) {
        viewport.scrollTop(Math.round(chatContentHeight - formerChatContentHeight));
      }
    }
  });

  viewport.on('ps-y-reach-start', _.throttle(() => {
    formerChatContentHeight = this.$('#channel-chat-content').height();

    let lmt = this.limit.get();
    formerLimit = lmt;
    
    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.channel_chatroom.onDestroyed(function () {
  formerLimit = null;
  formerTimestamp = null;
  formerChatContentHeight = null;
});

Template.channel_chatroom.helpers({
  results: function () {
    const results = [];
    const array = clientChannelMessages.find({}, {
      limit: Template.instance().limit.get(),
      sort: {
        createdAt: -1
      }
    }).fetch();
    
    array.forEach((item, index) => {
      let thisTimestamp = moment(item.createdAt).unix();

      if (!formerTimestamp) {
        formerTimestamp = thisTimestamp;
      }

      let range = formerTimestamp - thisTimestamp;

      if (index === 0) {
        range = 300;
      }

      if (range >= 300) {
        formerTimestamp = thisTimestamp;
        item.showTime = true;
      }

      results.unshift(item);
    });

    return results;
  },

  loading: function () {
    return !Template.instance().resultsSub.ready();
  }
});
